import { Button, Space } from 'antd'
import React, { useEffect } from 'react'
import { useModel } from 'umi'
import styles from './index.less'
import { FullscreenOutlined, FullscreenExitOutlined } from '@ant-design/icons'
import { useFullscreen, useMount, useUnmount } from '@umijs/hooks'
import AvatarDropdown from './AvatarDropdown'
import { warn, alarm } from '@/components/Alarm'
import { MqttClient } from '@/utils/mqtt'

export type SiderTheme = 'light' | 'dark'

const GlobalHeaderRight: React.FC<{}> = () => {
    const { initialState } = useModel('@@initialState')
    const { isFullscreen, toggleFull } = useFullscreen<HTMLElement>({
        dom: () => document.getElementById('root') as HTMLElement,
    })

    if (!initialState || !initialState.settings) {
        return null
    }

    const { navTheme, layout } = initialState.settings
    let className = styles.right
    useMount(() => {
        const userid = initialState.user?.userid
        const shareid = initialState.user?.share?.shareid
        const companyid = initialState.user?.companyid
        MqttClient.subscribe('public', 'all')
        if (userid) MqttClient.subscribe('user', userid)
        if (shareid) MqttClient.subscribe('share', shareid)
        if (companyid) MqttClient.subscribe('company', companyid)
        MqttClient.subscribe('message', 'alarm', (_, data) => {
            alarm(data.message || '未知')
        })
        MqttClient.subscribe('message', 'warn', (_, data) => {
            warn(data.message || '未知')
        })
    })
    useUnmount(() => {
        const userid = initialState.user?.userid
        const shareid = initialState.user?.share?.shareid
        const companyid = initialState.user?.companyid
        MqttClient.unsubscribe('public', 'all')
        if (userid) MqttClient.unsubscribe('user', userid)
        if (shareid) MqttClient.unsubscribe('share', shareid)
        if (companyid) MqttClient.unsubscribe('company', companyid)
    })
    if ((navTheme === 'dark' && layout === 'top') || layout === 'mix') {
        className = `${styles.right}  ${styles.dark}`
    }
    return (
        <Space className={className}>
            {isFullscreen ? (
                <FullscreenExitOutlined onClick={toggleFull} />
            ) : (
                <FullscreenOutlined onClick={toggleFull} />
            )}
            <AvatarDropdown menu={true} />
        </Space>
    )
}
export default GlobalHeaderRight
